package com.quanshu.exchange.ui.gui.message.mass_send;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 添加成员
 * Created by xiniu003 on 2017/12/11.
 */

public class AddMemberActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.add_member_group_rel)
    RelativeLayout addMemberGroupRel;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ok_btn)
    ImageView okBtn;
    @BindView(R.id.add_member_label_rel)
    RelativeLayout addMemberLabelRel;

    private SingleAdapter<UserEntity> adapter;
    private List<UserEntity> userList;
    private List<UserEntity> beSelectedUser;
    private HashMap<String, List<String>> beSelectedLabel;
    private List<GroupEntity> beSelectedGroup;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_member);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        beSelectedUser = (List<UserEntity>) getIntent().getSerializableExtra("List<UserEntity>");
        beSelectedGroup = (List<GroupEntity>) getIntent().getSerializableExtra("List<GroupEntity>");
        beSelectedLabel = (HashMap<String, List<String>>) getIntent().getSerializableExtra("HashMap<String, List<String>>");
        if (beSelectedUser == null) {
            beSelectedUser = new ArrayList<>();
        }
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<UserEntity>(this, R.layout.item_select_friend_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<UserEntity> wrapper, UserEntity item, int position) {
                holder.setRoundImageUrl(R.id.friend_avatar, item.getAvatar(), R.drawable.default_avatar);
                holder.setText(R.id.friend_name, AppUtils.getUserName(item));
                String letter = AppUtils.getUserInitialLetter(item);
                // 处理分割线
                int nextPosition = position + 1;
                if (nextPosition < userList.size()) {
                    UserEntity nextUser = userList.get(position + 1);
                    String nextHead = AppUtils.getInitialLetter(AppUtils.getUserName(nextUser));
                    if (letter.equals(nextHead)) {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.VISIBLE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.GONE);
                    }
                }
                if (position == userList.size() - 1) {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.GONE);
                }
                // 处理head字母
                if (position == 0) {
                    holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                    holder.setText(R.id.friend_sort_letter, letter);
                } else {
                    int lastPosition = position - 1;
                    if (lastPosition < 0) {
                        lastPosition = 0;
                    }
                    UserEntity lastUser = userList.get(lastPosition);
                    if (letter.equals(AppUtils.getUserInitialLetter(lastUser))) {
                        holder.setVisibility(R.id.friend_sort_letter, View.GONE);
                    } else {
                        holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                        holder.setText(R.id.friend_sort_letter, letter);
                    }
                }
                ImageView checkBox = holder.getView(R.id.friend_check);
                if (CheckUtil.isValidate(beSelectedUser)) {
                    for (UserEntity userEntity : beSelectedUser) {
                        if (userEntity.getMemberid().equals(item.getMemberid())) {
                            checkBox.setSelected(true);
                            break;
                        } else {
                            checkBox.setSelected(false);
                        }
                    }
                } else {
                    checkBox.setSelected(false);
                }
                checkBox.setOnClickListener(view -> {
                    boolean status = checkBox.isSelected();
                    if (beSelectedUser == null) {
                        beSelectedUser = new ArrayList<>();
                    }
                    if (!status) {
                        beSelectedUser.add(item);
                    } else {
                        Iterator<UserEntity> it = beSelectedUser.iterator();
                        while (it.hasNext()) {
                            if (it.next().getMemberid().equals(item.getMemberid())) {
                                it.remove();
                                break;
                            }
                        }
                    }
                    checkBox.setSelected(!status);
                    adapter.notifyDataSetChanged();
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        userList = UserDao.getInstance().queryForNoLabel();
        if (userList != null) {
            AppUtils.sortDataByPinYin(userList);
            adapter.setData(userList);
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        //选择群组
        RxViewHelper.getInstance().clicks(addMemberGroupRel, aVoid -> goSelectGroupActivity());

        RxViewHelper.getInstance().clicks(okBtn, aVoid -> doOk());

        RxViewHelper.getInstance().clicks(addMemberLabelRel, aVoid -> goSelectLabelActivity());
    }

    private void goSelectLabelActivity() {

        Intent intent = new Intent(this, SelectLabelFriendsListActivity.class);
        if (CheckUtil.isValidate(beSelectedLabel)) {
            intent.putExtra("HashMap<String, List<String>>", beSelectedLabel);
        }
        startActivityForResult(intent, 0x02);

    }

    private void goSelectGroupActivity() {
        Intent intent = new Intent(this, SelectGroupActivity.class);
        if (CheckUtil.isValidate(beSelectedGroup)) {
            intent.putExtra("List<GroupEntity>", (Serializable) beSelectedGroup);
        }
        startActivityForResult(intent, 0x01);
    }

    private void doOk() {
        Intent intent = getIntent();
        if (CheckUtil.isValidate(beSelectedUser)) {
            intent.putExtra("List<UserEntity>", (Serializable) beSelectedUser);
        }
        if (CheckUtil.isValidate(beSelectedGroup)) {
            intent.putExtra("List<GroupEntity>", (Serializable) beSelectedGroup);
        }
        if (CheckUtil.isValidate(beSelectedLabel)) {
            intent.putExtra("HashMap<String, List<String>>", beSelectedLabel);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {
                beSelectedGroup = (List<GroupEntity>) data.getSerializableExtra("List<GroupEntity>");
            } else if (requestCode == 0x02) {
                beSelectedLabel = (HashMap<String, List<String>>) data.getSerializableExtra("HashMap<String, List<String>>");
            }
        }
    }
}
